/*
 * @Author: sdq 483657864@qq.com
 * @Date: 2025-04-18 13:22:36
 * @LastEditors: sdq 483657864@qq.com
 * @LastEditTime: 2025-04-18 15:58:38
 * @FilePath: \ranyu_anchor_new\src\agroa\userCustomSub\subscribeUser.ts
 * @Description: 自定义订阅与否
 */
import { type UID } from "agora-rtc-sdk-ng";
export const customSubscribUser = async () => {
  // 引用导入
  const { agoraClient } = await import("../initAgoraSdk");
  const { useRemoteStore } = await import("@/store");
  const { handleError } = await import("../auxiliary");
  const remoteStore = useRemoteStore();
  /**
   * @description 用户手动订阅某个远端
   * @param {UID}uid - 目标用户ID
   */
  const subscribe = async (uid: UID) => {
    if (!agoraClient.value) return;
    // 从黑名单移除
    remoteStore.updateManualUnsubscribed("del", uid);
    const user = agoraClient.value.remoteUsers.find((u) => u.uid === uid);
    if (user) {
      try {
        await agoraClient.value.subscribe(user, "audio");
        user.audioTrack?.play();
        remoteStore.updateUserSubscription(uid, true);
        ElMessage.success(`手动订阅用户 ${uid} 成功`);
      } catch (error) {
        handleError("订阅失败", error);
      }
    }
  };
  /**
   * @description 用户手动取消订阅某个远端
   * @param {UID}uid - 目标用户ID
   */
  const unsubscribeUser = async (uid: UID) => {
    if (!agoraClient.value) return;
    //加入黑名单
    remoteStore.updateManualUnsubscribed("add", uid);
    const user = agoraClient.value.remoteUsers.find((u) => u.uid === uid);
    if (user) {
      try {
        await agoraClient.value.unsubscribe(user, "audio");
        remoteStore.updateUserSubscription(uid, false);
      } catch (error) {
        handleError("取消订阅失败", error);
      }
    }
  };
  return {
    subscribe,
    unsubscribeUser,
  };
};
